package com.thread.pool;

import java.util.concurrent.RecursiveAction;

// 继承 RecursiveAction 来实现可分解的任务
public class PrintTask extends RecursiveAction {

    // 每个小任务最多只打印五十个数
    public static final int THRESHOLD = 50;
    private int start;
    private int end;

    // 打印从start到end的任务
    public PrintTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected void compute() {
        // 当end与start之间的差小于THRESHOLD时，开始打印
        if (end - start < THRESHOLD) {
            for (int i = start; i < end; i++) {
                System.out.println(Thread.currentThread().getName() + "的i值" + i);
            }
        } else {
            // 当end与start之间的差大于THRESHOLD时，即要打印的数大于50个时，将大任务分解成两个小任务
            int middle = (start + end) / 2;
            PrintTask left = new PrintTask(start, middle);
            PrintTask right = new PrintTask(middle, end);
            // 并行执行两个小任务
            left.fork();
            right.fork();
        }
    }



}
